import React, { Component, Suspense } from "react";
import { formatMessage } from 'umi-plugin-react/locale';
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import { connect } from "dva";
import PageLoading from "@/components/PageLoading";
import GridContent from "@/components/PageHeaderWrapper/GridContent";
import { history, Link } from "umi";
import AddSystemKnowledge from "./add";
import UserSession from "@/UserSession";
import styles from "./detail.less";
import { robotCategoryEdit } from "@/services/systemKnowledge";
import { getRootCategoryInfo } from '@/services/knowledgeFile';
import { Card, Divider, Radio, Button } from "antd";

class SystemKnowledgeDetail extends Component {
	constructor(props) {
		super(props);
		this.state = {
			visible: false,
			list: [],
		};
	}

	componentDidMount() {
		const { dispatch } = this.props;
		this.info();
		
		dispatch({
			type: "global/changeLayoutCollapsed",
			payload: true,
		});
	}

	info = () => {
		let list = [];
		if (UserSession.hasDocKnowledge()) {
			list.push({ title: formatMessage({ id: 'systemKnowledgeBase.documentKnowledge' }), key: "file", icon: "filed", },);
		};
		list.push(
			list.push(
			{ title: formatMessage({ id: 'systemKnowledgeBase.qaKnowledge' }), key: "qa", icon: "wdzsd", })
		);
		list.push(
			{ title: formatMessage({ id: 'systemKnowledgeBase.keywordReply' }), key: "keywordReply", icon: "dldh" }
		);

		if (UserSession.hasAtlasKnowledge()) {
			list.push({ title: formatMessage({ id: 'systemKnowledgeBase.mapKnowledge' }), key: "graph", icon: "dtzsd", },);
		};
		if (UserSession.hasDialogKnowledge()) {
			list.push({ title: formatMessage({ id: 'systemKnowledgeBase.multiturnKnowledge' }), key: "dialog", icon: "dldh", },);
		};
		
		const { match: { url, params: { id }, } } = this.props;
		this.getDataInfo(id, res => {
			let type = res && res.type ? res.type : [];
			let typeList = list.filter(item => type.indexOf(item.key) > -1);
			this.setState({ list: [...typeList] });
		})
	}

	saveFormRef = (formRef) => {
		this.formRef = formRef;
	};

	handleCreate = () => {
		const { match: { url, params: { id }, }, location: { pathname, query }, history } = this.props;
		const form = this.formRef.props.form;
		form.validateFields(async (err, values) => {
			if (err) {
				return;
			};
			const res = await robotCategoryEdit({
				name: values.name, type: values.type,
				urlPrefix: UserSession.isSystemKnowledge() ? "headquarters" : null,
				id,
			});
			this.setState({ visible: false }, () => {
				this.info();
				if (values.type.indexOf(pathname.split('/')[pathname.split('/').length - 1]) > -1) {
					history.push({ pathname, query: { ...query, name: values.name } });
				} else {
					history.push({ pathname: url + `/${values.type[0]}`, query: { ...query, name: values.name } });
				}
			});
		});
	};

	getDataInfo = async (id, callback) => {
		let res = await getRootCategoryInfo({ id });
		console.log(res);
		callback(res);
	}

	editKnowledgeCard = async () => {
		const { match: { url, params: { id }, } } = this.props;
		this.getDataInfo(id, res => {
			this.setState({ visible: true }, () => {
				setTimeout(() => {
					this.formRef.props.form.setFieldsValue({ name: res?.name, type: res?.type })
				}, 300)
			})
		})
	}

	toBack = () => {
		const { location: { pathname, query }, history } = this.props;
		history.push({ pathname: UserSession.isSystemKnowledge() ? '/knowledgeDesign/systemKnowledge' : '/knowledgeDesign/myKnowledge', params: { current: query && query.current ? query.current : 1 } });
	}

	render() {
		const { list, active, visible } = this.state;
		const { match: { url, params: { id }, }, location: { pathname, query }, children, route } = this.props;
		// console.log('!!!', pathname);

		return (
			<GridContent>
				<Suspense fallback={<PageLoading />}>
					{pathname.indexOf("/dialog/add") != -1 || pathname.indexOf("/formInteraction/edit") != -1 ? null : (
						<Card style={{ marginBottom: 0, boxShadow: 'none', }} bordered={false} className={styles.card}>
							<div style={{ display: 'flex', margin: '0 -7px', alignItems: 'end', justifyContent: 'space-between' }}>
								{list && list.length > 0 ? (
									<Radio.Group size='large' value={list.filter((item) => pathname.indexOf(item.key) > -1)?.length > 0 ? list.filter((item) => pathname.indexOf(item.key) > -1)[0].key : ''}>
										{list.map((item, index) => {
											return (
												<Radio.Button value={item.key} key={index}>
													<Link to={{ pathname: pathname.indexOf("systemKnowledge") > -1 ? "/knowledgeDesign/systemKnowledge/" + id + "/" + item.key : "/knowledgeDesign/myKnowledge/" + id + "/" + item.key, query: query.libraryQuery ? JSON.parse(query.libraryQuery) : query, }}>
														<div key={item.key} style={{ display: "flex", alignContent: "center", alignItems: "center" }}>
															<img height="16" src={`/sysKnowledge/${list.filter((item) => pathname.indexOf(item.key) > -1)?.length > 0 && list.filter((item) => pathname.indexOf(item.key) > -1)[0].key == item.key ? item.icon + "-c" : item.icon}.png`} />
															<span style={{ marginLeft: 8, fontSize: '14px', color: list.filter((item) => pathname.indexOf(item.key) > -1).length > 0 && list.filter((item) => pathname.indexOf(item.key) > -1)[0].key == item.key ? "#3E5BFF" : "#333333", }}>{item.title}</span>
														</div>
													</Link>
												</Radio.Button>
											);
										})}
									</Radio.Group>
								) : null}
								<div>
									<Button icon="rollback" style={{ marginRight: 16 }} onClick={this.toBack}>
										{query && query.libraryQuery && JSON.parse(query.libraryQuery).name ? (
											JSON.parse(query.libraryQuery).name && JSON.parse(query.libraryQuery).name.length > 50 ? JSON.parse(query.libraryQuery).name.slice(0, 50) : JSON.parse(query.libraryQuery).name
										) : query.name ? query.name.length > 50 ? query.name.slice(0, 50) : query.name : formatMessage({ id: 'systemKnowledgeBase.returnToList' })}
									</Button>
									<Button icon='setting' onClick={this.editKnowledgeCard}>{formatMessage({ id: 'systemKnowledgeBase.settings' })}</Button>
								</div>
							</div>
						</Card>
					)}

					{/* {list.filter((item) => pathname.indexOf(item.key) > -1)[0].key == 'qa' ? (<Divider style={{ margin: 0 }} />) : null} */}
					{pathname.indexOf("/dialog/add") != -1 || pathname.indexOf("/formInteraction/edit/flow") != -1 ? null : <Divider style={{ margin: 0 }} />}

					<Card bordered={false} className={styles.body} bodyStyle={{ padding: 0, minHeight: '100%' }}>{children}</Card>
					<AddSystemKnowledge wrappedComponentRef={this.saveFormRef} visible={visible} onCancel={() => this.setState({ visible: false })} onCreate={this.handleCreate} />
				</Suspense>
			</GridContent>
		);
	}
}

export default connect()(SystemKnowledgeDetail);
